import hashlib
import json

from flask import Flask, request
from sqlalchemy import create_engine, Column, Integer, String, Table
from sqlalchemy.orm import sessionmaker, scoped_session, declarative_base

app = Flask(__name__)

# 创建一个引擎，目的是连接到我们的数据库上
engine = create_engine('mysql+pymysql://admin1:123@192.168.1.129:3306/mumushouji',echo=True)
# 打开数据库的连接会话
session = sessionmaker(engine)
# 保证线程安全
db_session = scoped_session(session)
# 获取基类
Base = declarative_base()


class User(Base):
    # 表结构的反射加载
    __table__ = Table("user",Base.metadata,autoload_with=engine)


@app.route("/",methods=["post"])
def reg():

    request_data = request.data
    request_data = json.loads(request_data)
    username = request_data["username"]
    password = request_data["password"]

    # 在正式查询数据库数据之前，我们需要做一个密码的md5格式转换
    password = hashlib.md5(password.encode()).hexdigest()
    nickname = request_data["nickname"]
    picture = request_data['picture']
    insert_data = {
        "username": username,
        "password": password,
        "nickname": nickname,
        "picture": picture
    }
    user = User(**insert_data)
    db_session.add(user)
    # 对数据做出改动需要进行提交
    db_session.commit()

    return "注册成功"

#  数据更新
#  思路是需要先查询出来要改动的行，然后再进行删除或者是更新
row = db_session.query(User).filter_by(user_id=140).first()
row.nickname="dada"
db_session.commit()

# 数据的删除
row = db_session.query(User).filter_by(user_id=140).delete()
db_session.commit()

if __name__ == "__main__":
    app.run()
